<?php
/**
 * Created by PhpStorm.
 * User: dongyanan
 * Date: 2019/7/4
 * Time: 10:36 AM
 */

namespace Ufile\Lumen\Ucloud;


class UcloudMultipartForm extends Ucloud
{
    public $Timeout = 0;

    public function __construct($bucket, $key, $file, $actionType = Ucloud::POSTFILE)
    {
        $this->key = $key;
        $this->file = $file;
        $this->bucket = $bucket;

        $this->path = $key;

        $this->setHost($bucket);
        $this->checkConfig($actionType);
        $this->getFileMimeType();
        $this->readFileContent();
    }

    public function setFormUpTimeOut($time)
    {
        $this->Timeout = $time;
    }

    public function clientCall()
    {
        $UCLOUD_PUBLIC_KEY = config('ufile.UCLOUD_PUBLIC_KEY');
        $UCLOUD_PRIVATE_KEY = config('ufile.UCLOUD_PRIVATE_KEY');

        $bucket = $this->bucket;
        $key = $this->path;
        $url = array();

        $url['host'] = $this->host;
        $url['path'] = '';

        $action_type = $this->actionType;
        $mimetype = $this->mimeType;
        $body = $this->content;

        $req = new HttpRequest('POST', $url, $body, $bucket, $key, $action_type);

        if ($this->Timeout){
            $req->setTimeOut($this->Timeout);
        }
        $req->Header['Expect'] = '';

        $ucloudAuth = new UcloudAuth($UCLOUD_PUBLIC_KEY,$UCLOUD_PRIVATE_KEY);
        $token = $ucloudAuth->SignRequest($req, $mimetype, Ucloud::HEAD_FIELD_CHECK);

        $fields = array('Authorization'=>$token, 'FileName' => $this->key);
        $files  = array('files'=>array('file', $this->file, $this->content, $this->mimeType));

        $http = new Http();
        list($contentType, $body) = $http->UCloud_Build_MultipartForm($fields,$files);

        if ($contentType === 'application/x-www-form-urlencoded') {
            if (is_array($req->Params)) {
                $body = http_build_query($req->Params);
            }
        }
        if ($contentType !== 'multipart/form-data') {
            $req->Header['Content-Type'] = $contentType;
        }
        $req->Body = $body;
        $token = $ucloudAuth->SignRequest($req, Ucloud::NO_AUTH_CHECK, Ucloud::HEAD_FIELD_CHECK);
        $req->Header['Authorization'] = $token;

        list($resp, $err) = $http->UCloud_Client_Do($req);

        if ($err !== null) {
            return array(
                'code' => $err->Code,
                'msg' => $err->ErrMsg
            );
        }

        list($data, $errClient) = $http->UCloud_Client_Ret($resp);

        if ($errClient !== null) {
            return array(
                'code' => $err->Code,
                'msg' => $err->ErrMsg
            );
        }

        return array(
            'code' => '200',
            'msg' => $data['ETag']
        );
    }
}